﻿using System.Runtime.InteropServices.JavaScript;
using System;

namespace _观察者模式
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var subject = new ConcreteSubject();
            var observer1 = new ConcreteObserver("Observer 1");
            var observer2 = new ConcreteObserver("Observer 2");

            subject.Attach(observer1);
            subject.Attach(observer2);

            subject.SetState("New state!");

            subject.Detach(observer2);

            subject.SetState("Another state!");
        }

    }
    public interface IObserver
    {
        void Update(string newState);
    }
    interface ISubject
    {
        void Attach(IObserver observer);
        void Detach(IObserver observer);
        void Notify();

    }
    public class ConcreteSubject : ISubject
    {
        private List<IObserver> observers = new List<IObserver>();
        private string state;

        public void Attach(IObserver observer)
        {
            observers.Add(observer);
        }

        public void Detach(IObserver observer)
        {
            observers.Remove(observer);
        }

        public void Notify()
        {
            foreach (var observer in observers)
            {
                observer.Update(state);
            }
        }

        public void SetState(string newState)
        {
            state = newState;
            Notify();
        }
    }


    public class ConcreteObserver : IObserver
    {
        private string name;

        public ConcreteObserver(string name)
        {
            this.name = name;
        }

        public void Update(string newState)
        {
            Console.WriteLine($"Observer {name} received the new state: {newState}");
        }
    }
}
